package xml.sax;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.*;

public class SAXPrinter extends DefaultHandler{

	public void startDocument(){
		//输出XML申明
		System.out.println("<?xml version='1.0' encoding='GB2312' ?>");
		
	}
	public void processingInstruction(String target,String data){
		//输出文档中的处理指令
		System.out.println("<?"+target+" "+data+"?>");
	}
	public void startElement(String uri,String localName,
			String qName,Attributes attrs){
		//输出元素的开始标签及其属性
		System.out.println("<"+qName);
		int len=attrs.getLength();
		for(int i=0;i<len;i++){
			System.out.println(" ");
			System.out.println(attrs.getQName(i));
			System.out.println("=\"");
			System.out.println(attrs.getValue(i));
			System.out.println("\"");
		}
		System.out.println(">");
	}
	public void characters(char[] ch,int start,int length){
		//输出元素的字符数据内容
		System.out.println(new String(ch,start,length));
	}
	public void endElement(String uri,String localName,String qName){
		//输出元素的结尾标签
		System.out.println("</"+qName+">");
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SAXParserFactory spf=SAXParserFactory.newInstance();
		SAXParser sp=null;
		try {
			sp=spf.newSAXParser();
			File file=new File("gril.xml");
			sp.parse(file,new SAXPrinter());
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
